<template>
  <div>
    <el-tabs v-model="activeName" type="card" tab-position="top" @tab-click="">
      <el-tab-pane label="表格" name="table">
        <virtual-scroll
          ref="virtualScroll"
          :data="list"
          :item-size="44"
          key-prop="id"
          @change="renderData => (virtualList = renderData)"
        >
          <!-- :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" -->
          <el-table
            :data="virtualList"
            style="width: 100%"
            row-key="id"
            :height="height"
            @select="onSelect"
            @select-all="onSelectAll"
            @selection-change="handleSelectionChange"
          >
            <virtual-column
              width="60"
              type="selection"
              :selectable="getSelectable"
            ></virtual-column>
            <virtual-column type="expand">
              <template slot-scope="props">
                <el-table
                  :data="props.row.children"
                  @select="onSelect2"
                  @select-all="onSelectAll2"
                  @selection-change="handleSelectionChange2"
                >
                  <el-table-column prop="ziduan1" label="字段1" width="">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.ziduan1"
                        placeholder="请输入"
                        size="small"
                        clearable
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="ziduan2" label="字段2" width="">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.ziduan2"
                        placeholder="请输入"
                        size="small"
                        clearable
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="ziduan3" label="字段3" width="">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.ziduan3"
                        placeholder="请输入"
                        size="small"
                        clearable
                      ></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </virtual-column>

            <el-table-column prop="date" label="日期" width="180"></el-table-column>
            <el-table-column prop="name" label="姓名" width="180"></el-table-column>
            <el-table-column prop="address" label="地址">
              <template slot-scope="scope">
                <el-select
                  size="small"
                  v-model="scope.row.address"
                  placeholder="请选择"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="备注">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.text"
                  placeholder="请输入"
                  size="small"
                  clearable
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="view(scope.row)">查看</el-button>
                <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </virtual-scroll>
      </el-tab-pane>
      <el-tab-pane label="图片" name="picture">
        <div class="pic_scroller">
          <img
            v-for="i in 100"
            src=""
            :data-src="getSrc(i)"
            onerror="this.src='./static/image/nopic.jpeg'"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import VirtualScroll, { VirtualColumn } from 'el-table-virtual-scroll';
  export default {
    components: {
      VirtualScroll,
      VirtualColumn,
    },
    data() {
      return {
        multipleSelection: [],
        multipleSelection2: [],
        activeName: 'table',
        height: 0,
        virtualList: [],
        list: [],
        observer: null,
        options: [
          { label: '北京', value: 110 },
          { label: '上海', value: 111 },
          { label: '天津', value: 112 },
          { label: '重庆', value: 113 },
        ],
      };
    },
    methods: {
      getSelectable(row, idx) {
        return true;
      },
      handleSelectionChange2(val) {
        console.log('multipleSelection', val);
        this.multipleSelection2 = val;
      },
      onSelect2(selection, row, checked) {
        console.log('select:', selection, row, checked);
      },
      onSelectAll2(selection, checked) {
        console.log('select-all:', selection, checked);
      },
      handleSelectionChange(val) {
        console.log('multipleSelection', val);
        this.multipleSelection = val;
      },
      onSelect(selection, row, checked) {
        console.log('select:', selection, row, checked);
      },
      onSelectAll(selection, checked) {
        console.log('select-all:', selection, checked);
      },
      view(row) {
        alert(row.id);
      },
      edit(row) {
        alert(row.id);
      },
      getSrc(i) {
        return 'https://picsum.photos/200/300' + '?_' + i;
      },
      loadImage(image) {
        const src = image.getAttribute('data-src');
        if (src) {
          image.setAttribute('src', src);
          image.removeAttribute('data-src');
        }
      },
      lazyLoad() {
        if ('IntersectionObserver' in window) {
          this.observer = new IntersectionObserver(
            entries => {
              entries.forEach(entry => {
                if (entry.isIntersecting) {
                  this.loadImage(entry.target);
                  this.observer.unobserve(entry.target);
                }
              });
            },
            {
              root: null,
              rootMargin: '0px', // 可以设置根元素的边距
              threshold: 0.1, // 当图片的 10% 进入视口时触发加载
            }
          );
          const images = document.querySelectorAll('img[data-src]');
          images.forEach(img => {
            this.observer.observe(img);
          });
        } else {
          try {
            document.querySelectorAll('img[data-src]').forEach((img, index) => {
              if (index < 20) {
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
              } else {
                throw new Error('中断循环');
              }
            });
          } catch (error) {}
          let container = document.querySelector('.el-main');
          container.addEventListener('scroll', () => {
            document.querySelectorAll('img[data-src]').forEach(img => {
              if (this.isInViewport(img)) {
                img.src = img.dataset.src;
                img.removeAttribute('data-src');
              }
            });
          });
        }
      },
      isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
          rect.top >= 0 &&
          rect.left >= 0 &&
          rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) + 280 &&
          rect.right <= (window.innerWidth || document.documentElement.clientWidth) + 150
        );
      },
      load(tree, treeNode, resolve) {
        setTimeout(() => {
          resolve([
            {
              id: new Date().getTime(),
              date: '2016-05-01',
              name: `王小虎${tree.id + 10000} `,
              address: '', //`上海市普陀区金沙江路 ${tree.id + 10000} 弄`,
              text: '',
            },
            {
              id: new Date().getTime() + 1,
              date: '2016-05-01',
              name: `王小虎${tree.id + 10001} `,
              address: '', //`上海市普陀区金沙江路 ${tree.id + 10001} 弄`,
              text: '',
            },
          ]);
        }, 200);
      },
    },
    created() {
      this.height = window.innerHeight - 160 + 'px';
      for (let i = 0; i < 10000; i++) {
        this.list.push({
          id: i + 1,
          date: '2016-07-01',
          name: `王小虎 ${i + 1} `,
          address: '', //`上海市普陀区金沙江路 ${i + 1} 弄`,
          text: '',
          hasChildren: true,
          children: [{ ziduan1: '1', ziduan2: '2', ziduan3: '3' }],
        });
      }
      // this.$refs.virtualScroll.addEventListener("scroll", () => {
      //   console.log("scroll");
      // });
    },
    mounted() {
      this.$nextTick(() => {
        this.lazyLoad();
      });
    },
    beforeDestroy() {
      if (this.observer) {
        this.observer.disconnect();
      }
      let container = document.querySelector('.el-main');
      container.removeEventListener('scroll');
    },
  };
</script>

<style lang="scss" scoped>
  .pic_scroller {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: stretch;
    justify-content: space-evenly;
    flex-flow: row wrap;
    img {
      cursor: pointer;
      width: 200px;
      height: 300px;
      margin-bottom: 30px;
      flex: 0 1 auto;
      // flex-grow: 0;
      // flex-shrink: 1;
      // flex-basis: auto;
    }
  }
</style>
